#include "symbollibrarydialog.h"
#include <QVBoxLayout>
#include <QFileDialog>
#include <QJsonArray>
#include <QJsonDocument>
#include <QFileInfo>
#include <QMessageBox>

SymbolLibraryDialog::SymbolLibraryDialog(QWidget* parent) : QDialog(parent)
{
    QVBoxLayout *layout = new QVBoxLayout(this);
    symbolList = new QListWidget(this);
    layout->addWidget(symbolList);

    addButton = new QPushButton("添加符号",this);
    deleteButton = new QPushButton("删除符号",this);
    loadButton = new QPushButton("载入符号",this);

    layout->addWidget(addButton);
    layout->addWidget(deleteButton);
    layout->addWidget(loadButton);

    //加载符号列表
    loadSymbolList();

    connect(addButton,&QPushButton::clicked,this,&SymbolLibraryDialog::onAddButtonClicked);

    connect(deleteButton,&QPushButton::clicked,this,&SymbolLibraryDialog::onDeleteButtonClicked);

    connect(loadButton,&QPushButton::clicked,this,&SymbolLibraryDialog::onLoadButtonClicked);

    //连接ListWidget双击事件
    connect(symbolList,&QListWidget::doubleClicked,this,[this](){
        emit symbolSelected(selectedSymbol());
    });
}

QString SymbolLibraryDialog::selectedSymbol() const
{
    QListWidgetItem *item = symbolList->currentItem();
    return item ? item->text() : QString();
}

void SymbolLibraryDialog::addSymbol(const QString &fileName)
{
    symbolList->addItem(fileName);
}

void SymbolLibraryDialog::loadSymbolList()
{
    QFile file("symbol_list.json");
    if (!file.open(QIODevice::ReadOnly)) return;

    QByteArray data = file.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    QJsonArray array = doc.array();

    for (const QJsonValue &value : array)
    {
        QString fileName = value.toString();
        QFileInfo info(fileName);
        addSymbol(info.fileName());
        //symbolPathMap[info.fileName()] = fileName;   // 保存文件名与路径的映射
    }
}

void SymbolLibraryDialog::saveSymbolList()
{
    QJsonArray array;
    for (int i = 0; i < symbolList->count(); ++i)
    {
        QListWidgetItem *item = symbolList->item(i);
        array.append(item->text());
    }

    QFile file("symbol_list.json");
    if (!file.open(QIODevice::WriteOnly)) return;

    QJsonDocument doc(array);
    file.write(doc.toJson());
}

void SymbolLibraryDialog::onAddButtonClicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, "保存进符号库", QDir::currentPath(), "JSON File(*.json)");
    if (!fileName.isEmpty())
    {
        QFileInfo info(fileName);
        addSymbol(info.fileName());
        saveSymbolList(); // 保存符号列表
        emit addSymbolInLib(fileName); // 发射信号通知主窗口
    }
}

void SymbolLibraryDialog::onDeleteButtonClicked()
{
    QListWidgetItem *item = symbolList->currentItem();
        if (item)
        {
            QString itemName = item->text(); // 获取列表中记录的文件路径
//            QString fileName = symbolPathMap[itemName];
//            QFile file(fileName);

            // 弹出确认对话框，避免误删
            QMessageBox::StandardButton reply;
            reply = QMessageBox::question(this, "确认删除",
                QString("确定要删除符号%1吗？").arg(itemName),
                QMessageBox::Yes | QMessageBox::No);

            if (reply == QMessageBox::Yes)
            {
                // 删除文件（如果存在）
//                if (file.exists())
//                {
//                    if (!file.remove())
//                    {
//                        QMessageBox::warning(this, "删除失败", "无法删除文件：" + fileName);
//                    }
//                }

                // 删除列表中的符号条目
                delete item;

                // 保存符号列表
                saveSymbolList();
            }
        }
}

void SymbolLibraryDialog::onLoadButtonClicked()
{
    emit symbolSelected(selectedSymbol());
}
